import React, { useEffect, useMemo, useState } from "react";
// @ts-ignore
import * as PANOLENS from "panolens";
// @ts-ignore
import THREE from "threejs";
import { getPanolens } from "./service";
// @ts-ignore
import DPlayer from 'dplayer'
import { Modal, message } from "antd";
import type { InfoSpotItem } from "@/pages/map/infospot/data";
import { base64Data, base64DataInfo, createImageFromText } from "./tools";
const Hls = require('hls.js')

function loadImage(url: string, callback: Function = (img: HTMLImageElement) => { }) {
    const img = new Image(); //创建一个Image对象，实现图片的预下载 
    img.setAttribute('crossorigin', 'anonymous');
    img.onload = function () {
        img.onload = null;
        callback(img);
    }
    img.src = url;
}
const map = {}
const mapData = {}
let player: any;
let loadingImg = false





const PreviewPanolens: React.FC<{ guid: string }> = ({ guid }) => {
    const viewer = useMemo(() => {
        const viewer = new PANOLENS.Viewer({
            container: document.getElementById(`container`),
            controlButtons: ['fullscreen'],
            cameraFov: 60,
            // autoRotate: true, //自动播放
            autoRotateActivationDuration: 2000, //时长
            autoRotateSpeed: 0.1, //速度
            clickTolerance: 0,
            autoHideInfospot: false,
        });
        return viewer;
    }, [guid])


    const toPanorama = async (item: InfoSpotItem) => {
        if (!map[item.to_panorama_id] || !mapData[item.to_panorama_id]) {
            message.loading('正在加载下一个场景，请稍等。。。。');
            await getData(item.to_panorama_id, false)
            // viewer.setPanorama(map[item.to_panorama_id])
            message.destroy()
        }
        const data = mapData[item.to_panorama_id]
        const panorama = map[item.to_panorama_id]

        viewer.setPanorama(panorama)
        if (item.camera_coordinates && Array.isArray(item.camera_coordinates)) {
            setTimeout(() => {
                viewer.camera.position.set(...item.camera_coordinates)
            }, 100)
        } else {
            if (data.coordinates && Array.isArray(data.coordinates)) {
                setTimeout(() => {
                    viewer.camera.position.set(...data.coordinates)
                }, 100)
            }
        }

    }

    const playerPlay = (item: InfoSpotItem) => {

        player = new DPlayer({
            container: document.getElementById('mse'),  // 注意：这里一定要写div的dom
            lang: 'zh-cn',
            video: {
                url: item.video[0],  // 这里填写.m3u8视频连接
                type: 'customHls',
                customType: {
                    customHls: function (video: any) {
                        const hls = new Hls()
                        hls.loadSource(video.src)
                        hls.attachMedia(video)
                    }
                }
            }
        })

        //     // 退出全屏销毁 视频
        player.on('fullscreen_cancel', function () {

            player.pause()
            player.destroy()
        })
        // player.reload()
        player.play()
        // player.getFullscreen(player.root || undefined)
        player.fullScreen.request('browser');
        player.on('ended', () => {
            // player.exitFullscreen(player.root || undefined)
            player.fullScreen.cancel('browser');
            toPanorama(item)
        })
    }

    const getData = async (id: string, tag = true) => {
        if (!id && typeof id !== 'string') {
            return message.error('参数缺失')
        }
        const item = await getPanolens({ guid: id })
        if (item) {
            const panorama = new PANOLENS.ImagePanorama(item.url + '?x-oss-process=style/img_compress');
            // const panorama = new PANOLENS.ImagePanorama(item.url);
            item.info_spot.forEach(async (item: any, index: number) => {
                // 排除已禁用节点
                if (item.status !== 1) {
                    return
                }

                const temp = item?.to_panorama_id ? base64Data : base64DataInfo
                const infospot = new PANOLENS.Infospot(item?.to_panorama_id ? (500 + item.name.split('、').length * 250) : 700, await createImageFromText(item.name, 100, temp, item?.to_panorama_id, item))
                // infospot.addHoverText(item.name)
                infospot.position.set(...item.coordinates)
                panorama.add(infospot)
                // //存在 位置点可以到达其他位置
                if (item.to_panorama_id) {
                    infospot.addEventListener("click", async function () {
                        infospot.unlockHoverElement()
                        if (loadingImg) {
                            message.warning('当前场景正在加载，请加载完成后再尝试。。。。', 2);
                            return
                        }
                        if (item.video && Array.isArray(item.video) && item.video.length > 0) {
                            Modal.confirm({
                                title: '提示',
                                content: `(${item.name})可以进入下一个场景，这里有一段视频引导您怎么走（视频播放完毕自动进入下一场景），当然你也可以跳过播放视频直接进入下一个场景。`,
                                cancelText: '跳过',
                                okText: '播放',
                                onOk: (close) => {
                                    playerPlay(item)
                                    return close();
                                },
                                onCancel: (close) => {
                                    toPanorama(item)
                                    return close();
                                }
                            })


                        } else {
                            toPanorama(item)
                        }
                        // 监听播放完成跳转下个场景


                    });
                }

            })
            viewer.add(panorama)

            if (tag && item.coordinates && Array.isArray(item.coordinates)) {
                viewer.camera.position.set(...item.coordinates)
            }
            map[item.guid] = panorama
            mapData[item.guid] = item
            setTimeout(() => {
                loadingImg = true
                loadImage(item.url + '?x-oss-process=style/img_vague', (url: HTMLImageElement) => {
                    loadingImg = false
                    panorama.load(url)
                })
                // loadImage(item.url, (url: HTMLImageElement) => {
                //     loadingImg = false
                //     panorama.load(url)
                // })
            }, 1000)
        } else {
            return message.error('参数缺失')
        }


    }



    useEffect(() => {
        getData(guid)
        return () => {
            if (player && player?.destroy) {
                player.destroy()
            }
        }
    }, [guid])


    return <>
        <div id='container' style={{ width: '0px', height: '0px' }} />
        {/* <div id="mse">

        </div> */}
        <div id="mse" style={{ position: 'fixed', top: '-1000vh', left: '-1000vw' }} />
    </>

}

export default PreviewPanolens